package com.cd.university.service.impl;

import com.cd.university.common.utils.RoleNameAndPerName;
import com.cd.university.db.mapper.PermissionMapper;
import com.cd.university.db.mapper.RoleMapper;
import com.cd.university.db.pojo.Role;
import com.cd.university.service.RoleService;
import com.cd.university.vo.RoleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈栋
 * @create 2021/9/3 19:14
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public String searchRoleName(int roleId) {
        String roleName = roleMapper.selectByPrimaryKey(roleId).getRoleName();
        return roleName;
    }

    @Override
    public List<String> searchPreNameByRid(int roleId) {
        return permissionMapper.searchPreNameByRid(roleId);
    }

    @Override
    public List<RoleVo> searchAllRole() {
        List<Role> roles = roleMapper.searchAllRole();
        ArrayList<RoleVo> roleVos = new ArrayList<>();

        for (Role role : roles) {
            roleVos.add(roleToRoleVo(role));
        }

        return roleVos;
    }

    @Override
    public int insertRoleName(Role role) {
        return roleMapper.insertSelective(role);
    }

    @Override
    public void deleteRole(Integer roleId) {
        roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public void updateRole(Integer roleId, String roleName) {
        Role role = new Role();
        role.setRoleId(roleId);
        role.setRoleName(roleName);

        roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public List<RoleNameAndPerName> searchRoleIdAndPerName() {
        return roleMapper.searchRoleIdAndPerName();
    }

    private RoleVo roleToRoleVo(Role role) {
        RoleVo roleVo = new RoleVo();
        BeanUtils.copyProperties(role, roleVo);
        return roleVo;
    }


}
